using System;
using System.Collections.Generic;
using System.Text;

namespace Decav.Gatsb.Application
{
    /// <summary>
    /// Gets the current instance of the <see cref="GatsbServiceApplication"/> for the current thread.
    /// </summary>
    public class GatsbServiceApplicationProvider : IGatsbApplicationProvider
    {
        public GatsbServiceApplicationProvider()
        {
            if (_current != null)
                throw new InvalidOperationException("Cannot create more than one instance of the GatsbServiceApplicationProvider.  The provider is a singleton.");

            _current = this;
        }

        [ThreadStatic]
        private GatsbServiceApplication _threadInstance;

        #region IGatsbApplicationProvider Members

        public GatsbApplication GetCurrentApplicationInstance()
        {
            if (_threadInstance == null)
                throw new InvalidOperationException("Cannot get the current application instance because the current thread does not have an application instance.");

            return _threadInstance;
        }

        /// <summary>
        /// Creates a new application instance on this thread, discarding the old instance.
        /// </summary>
        public void CreateNewInstance()
        {
            _threadInstance = new GatsbServiceApplication();
        }

        private static GatsbServiceApplicationProvider _current;

        /// <summary>
        /// Gets the provider singleton instance of the current application.
        /// </summary>
        public static GatsbServiceApplicationProvider Current
        {
            get
            {
                GatsbApplication.EnsureProviderCreated();
                return _current;
            }
        }

        #endregion
    }
}
